package c.w.connection;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.apache.mina.core.filterchain.DefaultIoFilterChain;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import android.os.SystemClock;

import c.w.base.dto.BaseMessage;
import c.w.constants.SystemConstants;
import c.w.utils.ConfigFactory;


public class ConnServeice {

	private void callService(int port, ProtocolCodecFilter filter, int minimumConnectTimeout, IoHandler handler) {
		NioSocketConnector connector = new NioSocketConnector();
		
		connector.addListener(null);
		
		DefaultIoFilterChainBuilder chan = connector.getFilterChain();
		
		chan.addLast("filter", filter);
		
		connector.setHandler(handler);
		
		connector.setConnectTimeoutCheckInterval(minimumConnectTimeout);
		
		//根据主机名构建连接
		ConnectFuture cf = connector.connect(new InetSocketAddress(SystemConstants.SERVICE_HOST, port));
		
		cf.awaitUninterruptibly();
		cf.getSession().getCloseFuture().awaitUninterruptibly();
		
		connector.dispose();
	}
	
	public void baseService() {
		int basePort = Integer.parseInt(ConfigFactory.getPropertiesValueByKey(SystemConstants.CONFIG_PROPERTIES_PROT_PATH, 
				SystemConstants.CONFIG_PROPERTIES_PROT_FILE_NAME, "baseConnPort"));
//		int basePort = 2013;
		
		//连接过期时间
		int minimumConnectTimeout = 30;
		
		ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
		
		callService(basePort, filter, minimumConnectTimeout, new ConnBaseServiceHandler());
	}
	
	public void inviteService() {
		int invitePort = Integer.parseInt(ConfigFactory.getPropertiesValueByKey(SystemConstants.CONFIG_PROPERTIES_PROT_PATH, 
				SystemConstants.CONFIG_PROPERTIES_PROT_FILE_NAME, "inviteConnPort"));
//		int invitePort = 2014;
		
		//连接过期时间
		int minimumConnectTimeout = 30;
		
		ProtocolCodecFilter filter = new ProtocolCodecFilter(new ObjectSerializationCodecFactory());
		
		BaseMessage bm = new BaseMessage();
		
		bm.setBaseGrade(10);
		bm.setFriendlyGrade(10);
		bm.setVipGrade(10);
		
		callService(invitePort, filter, minimumConnectTimeout, new ConnInviteServiceHandler());
	}
	
	/*public void callBaseService() throws Exception {
		
		long beginTime = System.currentTimeMillis();
		
		InetAddress serverAddr = InetAddress.getByName("10.0.2.2");
		
		System.out.println("serverAddr----"+serverAddr.toString());
		
        for (int i = 0; i < 100; i++) {
            Socket socket = null;  
            ObjectOutputStream os = null;  
            ObjectInputStream is = null;  
              
            try {  
                socket = new Socket(serverAddr, 2013);  
      
                os = new ObjectOutputStream(new BufferedOutputStream(socket.getOutputStream()));  
                BaseMessage baseMessage = new BaseMessage();
                baseMessage.setBaseGrade(i);
                baseMessage.setFriendlyGrade(i);
                baseMessage.setVipGrade(i);
                os.writeObject(baseMessage);  
                os.flush();  
                  
                is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));  
                Object obj = is.readObject();  
                if (obj != null) {  
                	baseMessage = (BaseMessage)obj;  
                	System.out.println(i +"--baseMessage: " + baseMessage.getBaseGrade() + " / " + baseMessage.getFriendlyGrade() +" / "+baseMessage.getVipGrade());  
                }  
            } catch(IOException ex) {  
                System.out.println("IO异常");
                ex.printStackTrace();
            } finally {  
                try {  
                    is.close();  
                } catch(Exception ex) {}  
                try {  
                    os.close();  
                } catch(Exception ex) {}  
                try {  
                    socket.close();  
                } catch(Exception ex) {}  
            }  
        }
        
        long endTime = System.currentTimeMillis();
        System.out.println("总共用时---" +(endTime - beginTime));
    }*/  
	
	/*public static void main(String[] args) throws Exception {  
        for (int i = 0; i < 100; i++) {  
            Socket socket = null;  
            ObjectOutputStream os = null;  
            ObjectInputStream is = null;  
              
            try {  
                socket = new Socket("localhost", 2013);  
      
                os = new ObjectOutputStream(socket.getOutputStream());  
                BaseMessage baseMessage = new BaseMessage();
                baseMessage.setBaseGrade(i);
                baseMessage.setFriendlyGrade(i);
                baseMessage.setVipGrade(i);
                os.writeObject(baseMessage);  
                os.flush();  
                  
                is = new ObjectInputStream(new BufferedInputStream(socket.getInputStream()));  
                Object obj = is.readObject();  
                if (obj != null) {  
                	baseMessage = (BaseMessage)obj;  
                	System.out.println("baseMessage: " + baseMessage.getBaseGrade() + " / " + baseMessage.getFriendlyGrade() +" / "+baseMessage.getVipGrade());  
                }  
            } catch(IOException ex) {  
                System.out.println("IO异常");
                ex.printStackTrace();
            } finally {  
                try {  
                    is.close();  
                } catch(Exception ex) {}  
                try {  
                    os.close();  
                } catch(Exception ex) {}  
                try {  
                    socket.close();  
                } catch(Exception ex) {}  
            }  
        }  
    }  */
}
